<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            @handleEvent="handleEventForm"
          >
            <template v-slot:form-depotName>
              <el-input
                v-model="formInfo.data.depotName"
                type="input"
                :class="type === 'update' ? 'not-mongolia' : ''"
                :disabled="true"
                placeholder="请选择仓库"
              >
                <template v-if="type === 'update'" #append>
                  <el-icon @click="openDepotWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-consumeTime>
              <el-time-picker
                v-model="formInfo.data.consumeTime"
                placeholder="请选择消耗时间"
                value-format="HH:mm:ss"
                :disabled="
                  type === 'update'
                    ? formInfo.data.autoConsume == 1
                      ? false
                      : true
                    : true
                "
              />
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip text="产品信息" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <new-page-filter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!isDisabled" @click="addProduct()"
                >添加产品
              </el-button>
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除产品
              </el-button>
            </template>
            <template v-slot:filter-batchHandle>
              <el-input-number
                v-model="filterInfo.data.highLevel"
                controls-position="right"
                style="width: 100px"
                placeholder="高水位"
                :step="1"
                :min="0"
                :max="9999999"
              />
              <el-button
                @click="batchHandle('highLevel')"
                style="margin-right: 10px"
                >批量设置高水位</el-button
              >
              <el-input-number
                v-model="filterInfo.data.lowLevel"
                controls-position="right"
                style="width: 100px"
                placeholder="低水位"
                :step="1"
                :min="0"
                :max="9999999"
              />
              <el-button @click="batchHandle('lowLevel')"
                >批量设置低水位</el-button
              >
            </template>
          </new-page-filter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :tab-index="true"
                row-key="id"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDepotInfo.query"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
    <!--选择产品-->
    <SelectProduct
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      :query="productInfo.query"
      @callback="selectProductCallback"
    />
  </div>
</template>

<script setup name="smartCabinetListModify">
import {
  bindProductSmartCabinet,
  updateSmartCabinet,
  getSmartCabinetListById,
  getSmartCabinetProductAll,
} from '@/api/smartCabinet'
import SelectProduct from './selectProduct'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: '',
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    smartCabinetId: props.id,
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'batchHandle' },
  ],
  data: {
    lowLevel: 0,
    highLevel: 0,
  },
})
const formInfo = ref({
  ref: null,
  data: {
    autoConsume: 0,
    temperatureHumitureMonitor: 0,
  },
  fieldList: [
    {
      label: '所属仓库',
      value: 'depotName',
      type: 'slot',
      required: true,
    },
    {
      label: '所属部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
      required: true,
    },
    {
      label: '客户端',
      value: 'clientId',
      type: 'select-model',
      code: 'client_id',
      required: true,
    },
    {
      label: '智能柜名称',
      value: 'name',
      type: 'input',
      required: true,
      disabled: props.type === 'update' ? false : true,
      maxlength: 32,
    },
    {
      label: '智能柜编码',
      value: 'code',
      type: 'input',
      required: true,
      disabled: props.type === 'update' ? false : true,
      maxlength: 32,
    },
    {
      label: '智能柜类型',
      value: 'type',
      type: 'select-model',
      code: 'smart_cabinet_type',
      required: true,
      disabled: props.type === 'update' ? false : true,
    },
    {
      label: '智能柜位置',
      value: 'address',
      type: 'input',
      disabled: props.type === 'update' ? false : true,
    },
    {
      label: '存储条件',
      value: 'storageCondition',
      type: 'select-model',
      code: 'smart_cabinet_storage_condition',
      required: true,
      disabled: props.type === 'update' ? false : true,
    },
    {
      label: '是否支持温湿度监控',
      value: 'temperatureHumitureMonitor',
      type: 'select-model',
      code: 'yes_or_no',
      required: true,
      disabled: props.type === 'update' ? false : true,
    },
    {
      label: '是否定时消耗',
      value: 'autoConsume',
      type: 'select-model',
      code: 'yes_or_no',
      event: 'autoConsume',
      disabled: props.type === 'update' ? false : true,
    },
    {
      label: '消耗时间(每天)',
      value: 'consumeTime',
      type: 'slot',
    },
    {
      label: '出柜消耗间隔',
      value: 'consumeIntervalTime',
      type: 'select-model',
      code: 'consume_interval_time',
      disabled: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      disabled: props.type === 'update' ? false : true,
    },
  ],
  rules: {},
  labelWidth: '120px',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '产品名称', value: 'commonName' },
    { label: '产品编码', value: 'productCode', minWidth: 80 },
    {
      label: '规格',
      value: 'standard',
      minWidth: 100,
    },
    {
      label: '单位',
      value: 'unitName',
      minWidth: 80,
    },
    {
      label: '厂家',
      value: 'brandName',
    },
    {
      label: '高水位',
      value: 'highLevel',
      type: 'number',
      width: '180px',
    },
    {
      label: '低水位',
      value: 'lowLevel',
      type: 'number',
      width: '180px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const productInfo = ref({
  visible: false,
  query: {
    status: 1,
    putShelfStatus: 1,
    idNotIn: '',
    deptId: '',
    codeTypeMult: '2,3',
  },
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 1,
    isCargoSpaceManage: 0,
  },
})
const formRefs = ref([])
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
const isDisabled = computed(() => {
  return formInfo.value.data.depotName && formInfo.value.data.deptName
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    emits('update:visible', val)
  },
})

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  initRules()
  if (props.id) {
    getMain()
  }
})
// 初始化校验规则
function initRules() {
  formInfo.value.rules = proxy.$initRules(formInfo.value.fieldList)
  formInfo.value.rules.consumeTime = [
    { required: false, message: '请选择消耗时间', trigger: 'change' },
  ]
  formInfo.value.rules.consumeIntervalTime = [
    { required: false, message: '请选择出柜消耗间隔', trigger: 'change' },
  ]
}
function handleEventForm(event, data) {
  if (event === 'autoConsume') {
    if (data == 1) {
      disabledFieldListItem(false, 'consumeIntervalTime')
      formInfo.value.rules.consumeTime[0].required = true
      formInfo.value.rules.consumeIntervalTime[0].required = true
    } else if (data == 0) {
      disabledFieldListItem(true, 'consumeIntervalTime')
      formInfo.value.data.consumeTime = ''
      formInfo.value.data.consumeIntervalTime = ''
      formInfo.value.rules.consumeTime[0].required = false
      formInfo.value.rules.consumeIntervalTime[0].required = false
    }
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//选择产品
function addProduct() {
  const productIds = tableInfo.value.data.map((item) => item.productId)
  productInfo.value.query.idNotIn = productIds.toString()
  productInfo.value.query.deptId = formInfo.value.data.deptId
  productInfo.value.visible = true
}
function selectProductCallback(rows = []) {
  if (rows.length) {
    tableInfo.value.data = rows.concat(tableInfo.value.data)
  }
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function batchHandle(str) {
  if (str === 'lowLevel') {
    if (tableInfo.value.selections && tableInfo.value.selections.length) {
      tableInfo.value.selections.forEach((item) => {
        item.lowLevel = filterInfo.value.data.lowLevel
      })
    } else {
      proxy.$message.warning('请勾选数据')
    }
  } else if (str === 'highLevel') {
    if (tableInfo.value.selections && tableInfo.value.selections.length) {
      tableInfo.value.selections.forEach((item) => {
        item.highLevel = filterInfo.value.data.highLevel
      })
    } else {
      proxy.$message.warning('请勾选数据')
    }
  }
}

function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function openDepotWindow() {
  selectDepotInfo.value.visible = true
}
function selectDepotCallBack(row) {
  if (row && row.id) {
    formInfo.value.data.depotId = row.id
    formInfo.value.data.depotName = row.name
    formInfo.value.data.deptId = row.deptId
    formInfo.value.data.deptName = row.deptName
  } else {
    formInfo.value.data.depotId = -2
    formInfo.value.data.depotName = ''
    formInfo.value.data.deptId = -2
    formInfo.value.data.deptName = ''
  }
  tableInfo.value.data = []
}

function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (tableInfo.value.data && tableInfo.value.data.length) {
      let commonName = tableInfo.value.data
        .filter((item) => parseInt(item.lowLevel) >= parseInt(item.highLevel))
        .map((item) => item.commonName)
      if (commonName.length) {
        proxy.$alert(
          `产品【${commonName}】的低水位应该小于高水位`,
          '操作提示',
          {
            confirmButtonText: '确定',
          }
        )
        return
      }
    }
    const params = {
      smartCabinetList: formInfo.value.data,
      mappingSmartCabinetProductList: tableInfo.value.data || [],
    }
    let api = undefined
    if (props.type === 'update') {
      //智能柜列表-修改
      api = updateSmartCabinet
    } else if (props.type === 'binding') {
      //智能柜列表-绑定产品
      api = bindProductSmartCabinet
    }
    api(params).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify')
      }
    })
  })
}
function disabledFieldListItem(disabled, nameValue) {
  let fieldList = formInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.disabled = disabled
    }
  })
}
function getMain() {
  getSmartCabinetListById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      if (formInfo.value.data.autoConsume == 1) {
        if (props.type === 'update') {
          disabledFieldListItem(false, 'consumeIntervalTime')
        }
        formInfo.value.rules.consumeTime[0].required = true
        formInfo.value.rules.consumeIntervalTime[0].required = true
      } else if (formInfo.value.data.autoConsume == 0) {
        disabledFieldListItem(true, 'consumeIntervalTime')
        formInfo.value.data.consumeTime = ''
        formInfo.value.data.consumeIntervalTime = ''
        formInfo.value.rules.consumeTime[0].required = false
        formInfo.value.rules.consumeIntervalTime[0].required = false
      }
    }
  })
  getList()
}
function getList() {
  getSmartCabinetProductAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
</script>

<style scoped></style>
